package com.century.sjt.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.webkit.WebView;
import android.widget.ProgressBar;

import com.century.sjt.R;

@SuppressWarnings("deprecation")
public class ProgressWebView extends WebView {
    private final static String TAG = ProgressWebView.class.getSimpleName();
    private ProgressBar progressBar;
    private Context context;

    public ProgressWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        progressBar = new ProgressBar(context, null, android.R.attr.progressBarStyleHorizontal);
        progressBar.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 12,0 ,0 ));
        progressBar.setProgressDrawable(getResources().getDrawable(R.drawable.webview_progressbar));
        addView(progressBar);
        setWebChromeClient(new WebChromeClient());
    }

    public class WebChromeClient extends android.webkit.WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
//            Log.e(TAG, "newProgress" + newProgress);
            if (newProgress ==100) {
                progressBar.setVisibility(GONE);
            } else {
                if (progressBar.getVisibility() == GONE)
                    progressBar.setVisibility(VISIBLE);
                progressBar.setProgress(newProgress);
            }
            super.onProgressChanged(view, newProgress);
        }

//        // 处理javascript中的console.log
//        @Override
//        public boolean onConsoleMessage(ConsoleMessage cm) {
//            android.util.Log.d(TAG, "webview console " + cm.lineNumber() + " of " + cm.sourceId() + " : " + cm.message());
//            return true;
//        }
//
//        // 处理javascript中的alert()
//        @Override
//        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
//            ToastUtil.showMessage(context, message, Toast.LENGTH_SHORT, Gravity.CENTER);
//            result.cancel();
//            return true;
//        }
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        LayoutParams lp = (LayoutParams) progressBar.getLayoutParams();
        lp.x = l;
        lp.y = t;
        progressBar.setLayoutParams(lp);
        super.onScrollChanged(l, t, oldl, oldt);
    }
}